let db = require("../db/db")
let ddl_handler = require("./custom/ddl_handler")

ddl_handler.set_db(db);

let handle = async function (action, data, login_info, req, res) {
	switch (action) {
		case "build":
			//console.log(data);
			let trans = await db.transaction(multi = true);
			try {
				//表单页面
				let form_page_params = {
					module: data.module,
					name: data.name,
					page_type_id: 13,
					desc: data.desc,
					property: JSON.stringify({
						page: data.html
					}),
					create_user: login_info.user_id
				}
				let sql = "insert into sys_page set ?";
				let r = await trans.add(sql, form_page_params);
				if (r instanceof Error) { return (r); trans.rollback(); }
				//功能权限(FORM)
				let page_id = r.results.insertId;
				let result = await ddl_handler.add_functions(page_id, 13, login_info, req, res);
				let form_func_id = result.results.insertId ? result.results.insertId : result.results[0].insertId;
				//赋权(CRUD、FORM、DATAMODEL)
				sql = "";
				let role_params = [];
				for (let role_id of data.roles.split(",")) {
					sql += "insert into sys_role_func_r set ?;";
					role_params.push({
						role_id: role_id,
						func_id: form_func_id
					});
				}
				r = await trans.add(sql, role_params);
				//菜单(FORM)
				let menu_params = {
					name: data.name,
					icon: "fa-code",
					parent_id: data.parent_menu,
					page_id: page_id,
					create_user: login_info.user_id
				}
				sql = "insert into sys_menu set ?";
				r = await trans.add(sql, menu_params);
				let menu_id = r.results.insertId;
				//提交全部事务
				await trans.commit();
				console.log("CRUD quick built successfully!");
				return ({ page_id: page_id, menu_id: menu_id });
			}
			catch (err) {
				trans.rollback();
				throw (err);
			}
			break;
		default:
			return (Error('未知的action:' + action));
	}
}

module.exports = { handle };